# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger


__all__ = ['PromAlarmTemplate']

class PromAlarmTemplate(Base, SessionMixin):
    '''
    告警模板
    '''
    __tablename__ = "prom_alarm_template"
    name = Column(String(256), nullable=False, index=True, comment='模板名称')
    # bind or auto
    type = Column(String(16), default="bind", nullable=False, index=True, comment='模板分类')
    classes = Column(String(128), nullable=False, index=True, comment='模板归类')
    # true/false 是否需要同步更新
    is_update = Column(Boolean, default=text('True'), nullable=False, comment='是否需要同步更新')
    comment = Column(String(256), nullable=True, comment='告警模板说明')

    strategies = relationship("PromAlarmStrategy", backref="alarm_template")


    __table_args__ = (
        Index('idx_prom_alarm_template_name', 'name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )


    def __repr__(self):
        return f"<prom_alarm_template='{self.name}>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        result["strategies"] = [
            strategy.object_to_dict(db)
            for strategy in self.strategies
        ]

        return result

    @classmethod
    def set_is_update(cls, db: Session, uuid: int, is_update: bool):
        template_info = cls.get_object_info_by_uuid(db, uuid)
        if template_info["is_update"] == is_update:
            return True

        template_info.pop("strategies")
        template_info["is_update"] = is_update
        return cls.update(db, template_info)


